import React, { useRef, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Jodit } from 'jodit';
import 'jodit/build/jodit.min.css';

const mimetypeToHtmlTagMap = {
  'image/png': 'img',
  'image/bmp': 'img',
  'image/jpeg': 'img',
  'image/gif': 'img',
  'image/webp': 'img',
  'video/webm': 'video',
  'video/ogg': 'video'
};

type FileType = {
  encoding: string;
  filename: string;
  mimetype: string;
  originalname: string;
  size: number;
};

export interface JoditRef {
  getValue(): string;
}

interface IProps {
  height?: number;
  initialValue?: string;
  placeholder?: string;
}

export default forwardRef(({ height, initialValue, placeholder }: IProps, ref: React.Ref<JoditRef>) => {
  const textArea = useRef<HTMLTextAreaElement>(null);
  const editorRef = useRef<any>(null);

  useImperativeHandle(ref, () => ({
    getValue: () => editorRef.current.value || ''
  }));

  useEffect(() => {
    const element = textArea.current;

    editorRef.current = Jodit.make(element!, {
      language: 'zh_cn',
      insertImageAsBase64URI: false,
      minHeight: height || 300,
      imagesExtensions: Object.values(mimetypeToHtmlTagMap),
      uploader: {
        url: '/bk/uploadIpfs/workflow?m=dev',
        filesVariableName: () => 'file',
        isSuccess: () => true,
        process(file: FileType) {
          return file;
        },
        defaultHandlerSuccess(file: FileType) {
          const editor = editorRef.current;
          const tag = mimetypeToHtmlTagMap[file.mimetype];

          if (tag) {
            const elm = editor.createInside.element(tag);

            elm.setAttribute('src', '/bk/getFile/' + file.filename);
            editor.s.insertImage(elm, null, editor.o.imageDefaultWidth);
          }
        }
      }
    });

    return () => {
      editorRef.current.destruct()
    }
  }, [height]);

  useEffect(() => {
    if (initialValue) {
      editorRef.current.value = initialValue;
    }
  }, [initialValue]);

  return (
    <textarea ref={textArea} placeholder={placeholder} />
  );
});